<template>
  <div class="basic-list-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb-nav">
      <el-breadcrumb-item :to="{ path: '/' }">首页(登录)</el-breadcrumb-item>
      <el-breadcrumb-item>溯源管理</el-breadcrumb-item>
      <el-breadcrumb-item>基本信息</el-breadcrumb-item>
    </el-breadcrumb>
    
    <div class="content-wrapper">
      <!-- 操作按钮区域 -->
      <el-card class="action-card" shadow="hover">
        <div class="action-header">
          <div class="action-buttons">
            <el-button type="primary" @click="addProduct" class="action-btn primary-btn">
              <el-icon><Plus /></el-icon>
              新增产品
            </el-button>
            <el-button type="success" @click="exportExcel" class="action-btn success-btn">
              <el-icon><Download /></el-icon>
              导出Excel表
            </el-button>
            <el-button type="danger" @click="deleteSelected" class="action-btn danger-btn">
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
          </div>
          <div class="status-indicators">
            <div class="status-item">
              <el-icon class="status-icon"><Lightning /></el-icon>
              <span class="status-text">系统运行中</span>
            </div>
            <div class="status-item">
              <el-icon class="status-icon"><Lightning /></el-icon>
              <span class="status-text">数据同步</span>
            </div>
            <div class="status-item">
              <el-icon class="status-icon"><Lightning /></el-icon>
              <span class="status-text">实时监控</span>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 数据表格 -->
      <el-card class="table-card" shadow="hover">
        <template #header>
          <div class="table-header">
            <h3 class="table-title">产品信息列表</h3>
            <div class="table-actions">
              <el-icon class="refresh-icon" @click="getBasicList" title="刷新数据">
                <Refresh />
              </el-icon>
            </div>
          </div>
        </template>
        
        <el-table 
          :data="BasicData" 
          class="data-table"
          v-loading="loading"
          @selection-change="handleSelectionChange"
          :header-cell-style="{ background: '#f8f9fa', color: '#2d5a27', fontWeight: '600' }"
          :cell-style="{ borderBottom: '1px solid #e9ecef' }"
        >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="75" align="center" />
        
        <!-- 商品名称列 -->
        <el-table-column prop="storeName" label="商品名称" align="center" min-width="150">
          <template #header>
            <div class="column-header">
              <div class="column-title">商品名称</div>
              <el-input 
                v-model="searchFilters.storeName" 
                placeholder="输入进行查询" 
                size="small" 
                class="search-input"
                @input="handleSearch"
                clearable
              />
            </div>
          </template>
        </el-table-column>
        
        <!-- 生产批次列 -->
        <el-table-column prop="batch" label="生产批次" align="center" min-width="120">
          <template #header>
            <div class="column-header">
              <div class="column-title">生产批次</div>
              <el-input 
                v-model="searchFilters.batch" 
                placeholder="输入进行查询" 
                size="small" 
                class="search-input"
                @input="handleSearch"
                clearable
              />
            </div>
          </template>
        </el-table-column>
        
        <!-- 保质期列 -->
        <el-table-column prop="expiration" label="保质期(天)" align="center" min-width="100">
          <template #header>
            <div class="column-header">
              <div class="column-title">保质期(天)</div>
              <el-input 
                v-model="searchFilters.expiration" 
                placeholder="输入进行查询" 
                size="small" 
                class="search-input"
                @input="handleSearch"
                clearable
              />
            </div>
          </template>
        </el-table-column>
        
        <!-- 生产许可证号列 -->
        <el-table-column prop="license" label="生产许可证号" align="center" min-width="150">
          <template #header>
            <div>
              <div>生产许可证号</div>
              <el-input 
                v-model="searchFilters.license" 
                placeholder="输入进行查询" 
                size="small" 
                style="margin-top: 5px;"
                @input="handleSearch"
              />
            </div>
          </template>
        </el-table-column>
        
        <!-- 生产企业列 -->
        <el-table-column prop="company" label="生产企业" align="center" min-width="200">
          <template #header>
            <div>
              <div>生产企业</div>
              <el-input 
                v-model="searchFilters.company" 
                placeholder="输入进行查询" 
                size="small" 
                style="margin-top: 5px;"
                @input="handleSearch"
              />
            </div>
          </template>
        </el-table-column>
        
        <!-- 信息完善度列 -->
        <el-table-column prop="completeness" label="信息完善度" align="center" min-width="150">
          <template #default="scoped">
            <div class="completeness-container">
              <el-progress 
                :percentage="scoped.row.completeness" 
                :color="getProgressColor(scoped.row.completeness)"
                :stroke-width="8"
                :show-text="true"
                :format="(percentage: number) => `${percentage}%`"
                class="completeness-progress"
              />
            </div>
          </template>
        </el-table-column>
        <!-- 创建人 -->
         <el-table-column prop="creator" label="创建人" align="center" min-width="120">
          <template #header>
            <div>
              <div>创建人</div>
              <!-- <el-input 
                v-model="searchFilters.creator" 
                placeholder="输入进行查询" 
                size="small" 
                style="margin-top: 5px;"
                @input="handleSearch"
              /> -->
            </div>
          </template>
        </el-table-column>
        <!-- 创建时间 -->
         <el-table-column prop="creatorDate" label="创建时间" align="center" min-width="180">
          <template #header>
            <div>
              <div>创建时间</div>
              <!-- <el-input 
                v-model="searchFilters.creatorDate" 
                placeholder="输入进行查询" 
                size="small" 
                style="margin-top: 5px;"
                @input="handleSearch"
              /> -->
            </div>
          </template>
          <template #default="{ row }">
            {{ formatDateTime(row.creatorDate) || row.creatorDate || '无数据' }}
          </template>
        </el-table-column>
        <!-- 修改人 -->
         <el-table-column prop="updator" label="修改人" align="center" min-width="120">
          <template #header>
            <div>
              <div>修改人</div>
              <!-- <el-input 
                v-model="searchFilters.updator" 
                placeholder="输入进行查询" 
                size="small" 
                style="margin-top: 5px;"
                @input="handleSearch"
              /> -->
            </div>
          </template>
        </el-table-column>
        <!-- 修改时间 -->
         <el-table-column prop="updatorDate" label="修改时间" align="center" min-width="180">
          <template #header>
            <div>
              <div>修改时间</div>
              <!-- <el-input 
                v-model="searchFilters.updatorDate" 
                placeholder="输入进行查询" 
                size="small" 
                style="margin-top: 5px;"
                @input="handleSearch"
              /> -->
            </div>
          </template>
          <template #default="{ row }">
            {{ row.updatorDate ? moment(row.updatorDate).format("YYYY-MM-DD HH:mm:ss") || row.updatorDate : '' }}
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" align="center" width="320" fixed="right">
          <template #default="scoped">
            <div class="action-buttons-cell">
              <el-button type="primary" size="small" @click="details(scoped.row)" class="table-action-btn detail-btn">
                详情
              </el-button>
              <el-button type="warning" size="small" @click="editProduct(scoped.row)" class="table-action-btn edit-btn">
                <el-icon><Lightning /></el-icon>
                修改
              </el-button>
              <el-button type="success" size="small" @click="exportTraceCode(scoped.row)" class="table-action-btn export-btn">
                导出溯源码
              </el-button>
              <el-button type="danger" size="small" @click="deleteProduct(scoped.row)" class="table-action-btn delete-btn">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="page.PageIndex"
            v-model:page-size="page.PageSize"
            :page-sizes="[1,2,3,4,5,10, 20, 50]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.totalCount"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="custom-pagination"
          />
        </div>
      </el-card>
    </div>

    <!-- 添加/编辑产品信息弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" draggable>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item label="商品名称:" prop="sid">
          <!-- <el-input v-model="formData.sid" placeholder="请输入商品名称">
            <template #suffix>
              <el-icon><ArrowDown /></el-icon>
            </template>
          </el-input> -->
          <el-select
        v-model="formData.sid"
        placeholder="请选择"
        clearable
      >
        <el-option v-for="item in StoreData" :label="item.storeName" :value="item.id" />
      </el-select>
        </el-form-item>
        
        <el-form-item label="生产批次:" prop="batch">
          <el-input v-model="formData.batch" placeholder="请输入生产批次" />
        </el-form-item>
        
        <el-form-item label="保质期(天):" prop="expiration">
          <el-input-number 
            v-model="formData.expiration" 
            :min="1" 
            :max="9999" 
            placeholder="请输入保质期"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="生产许可证号:" prop="license">
          <el-input v-model="formData.license" placeholder="请输入生产许可证号" />
        </el-form-item>
        
        <el-form-item label="生产企业:" prop="company">
          <el-input v-model="formData.company" placeholder="请输入生产企业" />
        </el-form-item>
        
        <el-form-item label="封面图:" prop="picture">
          <el-upload
            class="cover-uploader"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            :before-upload="beforeCoverUpload"
            action="http://localhost:5198/api/UpLoadFile/UploadFile"
          >
            <div class="cover-upload-box">
              <el-icon v-if="!formData.picture" class="cover-uploader-icon"><Plus /></el-icon>
              <img v-else :src="formData.picture" class="cover-image" />
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">
            <el-icon><Lightning /></el-icon>
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 二维码弹框 -->
    <QRCodeDialog
      v-model="qrCodeDialogVisible"
      :batch-data="currentBatchData"
      :traceability-data="traceabilityData"
    />
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import { ArrowRight, Plus, Delete, Lightning, ArrowDown, Refresh, Download } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { useCounterStore } from "@/stores/counter"
import { dataRead, dataWrite,Traceability } from '@/Utils/Http'
import moment from 'moment'
import type { UploadProps } from 'element-plus'
import QRCodeDialog from '@/components/QRCodeDialog.vue'

const stores=useCounterStore()

// 类型定义
interface BasictInfo {
  id: number,
  sid:string,
  storeName: string
  batch: string
  expiration: number
  license: string
  company: string
  picture: string
  completeness: number
  creator: string
  creatorDate: string
  updator: string
  updatorDate: string
}

interface SearchFilters {
  storeName: string
  batch: string
  expiration: string
  license: string
  company: string
  // creator: string
  // creatorDate: string
  // updator: string
  // updatorDate: string
}

interface Page {
  PageIndex: number
  PageSize: number
  totalCount: number
  pageCount: number
}

// 溯源数据接口定义
interface TraceabilityData {
  code: number
  message: string
  data: {
    basic: {
      id: number
      sid: number
      batch: string
      expiration: number
      license: string
      company: string
    }
    cultivation: {
      variety: string
      source: string
      rearingDays: number
      brand: string
      rearingLeader: string
      outDate: string
      batch: string
    }
    deepProcessing: {
      team: string
      leader: string
      batch: string
    }
    slaughter: {
      batch: string
      weight: number
    }
  }
}

// 变量初始化
const counter = useCounterStore()
const router = useRouter()
const route = useRoute()
const loading = ref(false)
const formRef = ref<FormInstance>()

// 数据相关
const BasicData = ref<any>([])
const selectedProducts = ref<BasictInfo[]>([])

// 搜索过滤条件
const searchFilters = reactive<SearchFilters>({
  storeName: '',
  batch: '',
  expiration: '',
  license: '',
  company: '',
  // creator: '',
  // creatorDate: '',
  // updator: '',
  // updatorDate: ''
})

// 分页
const page = reactive<Page>({
  PageIndex: 1,
  PageSize: 5,
  totalCount: 0,
  pageCount: 0
})

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加产品信息')

// 二维码弹框相关
const qrCodeDialogVisible = ref(false)
const currentBatchData = ref<BasictInfo | null>(null)
const traceabilityData = ref<TraceabilityData | null>(null)

// 表单数据
const formData = reactive<BasictInfo>({
  id: 0,
  sid: '',
  storeName: '',
  batch: '',
  expiration: 0,
  license: '',
  company: '',
  picture: '',
  completeness: 0,
  creator: stores.userInfo.userNickname,
  creatorDate: '2025-09-17',
  updator: stores.userInfo.userName,
  updatorDate: '2025-09-17'
})

// 表单验证规则
const formRules = reactive<FormRules<BasictInfo>>({
  sid: [
    { required: true, message: '请输入商品名称', trigger: 'change' }
  ],
  batch: [
    { required: true, message: '请输入生产批次', trigger: 'blur' },
     {
      pattern: /^[0-9A-Za-z]+$/,
      message: '只能输入数字和字母',
      trigger: ['blur', 'change']
    }
  ],
  expiration: [
    { required: true, message: '请输入保质期', trigger: 'blur' }
  ],
  license: [
    { required: true, message: '请输入生产许可证号', trigger: 'blur' },
     {
      pattern: /^[0-9A-Za-z]+$/,
      message: '只能输入数字和字母',
      trigger: ['blur', 'change']
    }
  ],
  company: [
    { required: true, message: '请输入生产企业', trigger: 'blur' }
  ],
  picture: [
    { required: true, message: '请上传封面图', trigger: 'change' }
  ]
})

// 生命周期钩子
onMounted(() => {
  getBasicList()
  GetStore()
})

// 监听分页变化
watch(page, () => {
  getBasicList()
})

// 获取产品列表
const getBasicList = () => {
  loading.value = true
  
  // 构建查询参数，只传递有值的参数
  const params: any = {
    PageIndex: page.PageIndex,
    PageSize: page.PageSize
  }
  
  // 只添加非空的搜索条件
  if (searchFilters.storeName && searchFilters.storeName.trim()) {
    params.StoreName = searchFilters.storeName.trim()
  }
  if (searchFilters.batch && searchFilters.batch.trim()) {
    params.Batch = searchFilters.batch.trim()
  }
  if (searchFilters.expiration && searchFilters.expiration.trim()) {
    params.Expiration = parseInt(searchFilters.expiration)
  }
  if (searchFilters.license && searchFilters.license.trim()) {
    params.License = searchFilters.license.trim()
  }
  if (searchFilters.company && searchFilters.company.trim()) {
    params.Company = searchFilters.company.trim()
  }
  
  // 实际API调用代码（注释掉）
  /**/
  Traceability.get('/Basic/GetBasicQuery', {
    params: params
  }).then(res => {
    BasicData.value = res.data.data.data
    page.totalCount = res.data.data.totalCount
    page.pageCount = res.data.data.pageCount
    // 调试：查看数据格式
    console.log('获取到的数据:', BasicData.value)
    if (BasicData.value && BasicData.value.length > 0) {
      console.log('第一条数据的创建时间:', BasicData.value[0].creatorDate)
      console.log('第一条数据的修改时间:', BasicData.value[0].updatorDate)
    }
  }).catch(err => {
    ElMessage.error('获取产品列表失败')
    console.error(err)
  }).finally(() => {
    loading.value = false
  })
}

// 搜索处理
const handleSearch = () => {
  page.PageIndex = 1
  getBasicList()
}

// 选择变化处理
const handleSelectionChange = (selection: BasictInfo[]) => {
  selectedProducts.value = selection
}

//绑定商品
const StoreData = ref<any>([])
const GetStore = () => {
  Traceability.get('/Basic/GetStore').then(res => {
    StoreData.value=res.data.data
  })
}

// 添加产品
const addProduct = () => {
  dialogTitle.value = '添加产品信息'
  formData.id = 0,
  formData.sid='',
  formData.batch = '',
  formData.storeName= '',
  formData.batch= '',
  formData.expiration= 0,
  formData.license= '',
  formData.company= '',
  formData.picture= '',
  formData.completeness= 0,
  // formData.creator= '',
  // formData.creatorDate= '',  
  dialogVisible.value = true
}

// 编辑产品
const editProduct = (row: BasictInfo) => {
  dialogTitle.value = '编辑产品信息'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除产品
const deleteProduct = (row: BasictInfo) => {
  ElMessageBox.confirm(
    `确定要删除产品"${row.storeName}"吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际API调用代码（注释掉）
    /**/
    Traceability.delete('/Basic/DelBasic?Id='+row.id).then(res => {
      if (res.data.code == 500) {
        ElMessage.success('删除成功')
        getBasicList()
      } else {
        ElMessage.error(res.data.message || '删除失败')
      }
    }).catch(err => {
      ElMessage.error('删除失败')
      console.error(err)
    })
    
    
    // 使用死值数据演示
    // ElMessage.success('删除成功（演示）')
    // getBasicList()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 批量删除
const deleteSelected = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择要删除的产品')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedProducts.value.length} 个产品吗？`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际API调用代码（注释掉）
    /**/
    const ids = selectedProducts.value.map(item => item.id)
    Traceability.post('/Basic/Handle', { ids }).then(res => {
      if (res.data.code == 500) {
        ElMessage.success('批量删除成功')
        getBasicList()
      } else {
        ElMessage.error(res.data.message || '批量删除失败')
      }
    }).catch(err => {
      ElMessage.error('批量删除失败')
      console.error(err)
    })
    
    
    // 使用死值数据演示
    // ElMessage.success(`批量删除成功（演示，删除了${selectedProducts.value.length}个产品）`)
    // getBasicList()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 导出Excel
const exportExcel = () => {
  loading.value = true
  ElMessage.info('正在导出Excel文件，请稍候...')
  
  Traceability.get('/Export/ExportExcel', {
    params: {
      PageIndex: page.PageIndex,
      PageSize: page.PageSize
    }
  }).then(res => {
    if (res.data.code === 200) {
      ElMessage.success('导出成功')
      // 创建下载链接
      const downloadUrl = res.data.data
      const link = document.createElement('a')
      link.href = downloadUrl
      link.download = '溯源基本信息.xlsx'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    } else {
      ElMessage.error(res.data.message || '导出失败')
    }
  }).catch(err => {
    ElMessage.error('导出失败')
    console.error(err)
  }).finally(() => {
    loading.value = false
  })
}

// 导出溯源码
const exportTraceCode = (row: BasictInfo) => {
  loading.value = true
  ElMessage.info('正在获取溯源信息，请稍候...')
  
  // 调用后端API获取批次对应的溯源信息
  Traceability.get('/Export/ExportTraceability', {
    params: {
      Batch: row.batch
    }
  }).then(res => {
    if (res.data.code == 200) {
      // 检查数据是否为空
      if (!res.data.data || !Array.isArray(res.data.data) || res.data.data.length === 0) {
        ElMessage.warning('该批次暂无溯源数据，请先完善养殖、屠宰、深加工信息')
        return
      }
      
      // 调试：打印API返回的数据结构
      console.log('API返回的溯源数据:', res.data)
      
      // 保存当前批次数据和溯源数据
      currentBatchData.value = row
      traceabilityData.value = res.data
      // 显示二维码弹框
      qrCodeDialogVisible.value = true
      
      ElMessage.success('溯源信息获取成功')
    } else {
      ElMessage.error(res.data.message || '获取溯源信息失败')
    }
  }).catch(err => {
    ElMessage.error('获取溯源信息失败')
    console.error(err)
  }).finally(() => {
    loading.value = false
  })
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: 0,
    productName: '',
    productionBatch: '',
    shelfLife: 90,
    licenseNumber: '',
    enterpriseName: '',
    coverImage: '',
    completeness: 100,
    createTime: ''
  })
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid) => {
    if (valid) {
      if (formData.id == 0) {
        // 添加产品
        // 实际API调用代码（注释掉）
        /**/
        Traceability.post('/Basic/AddBasic', formData).then(res => {
          if (res.data.code == 300) {
            ElMessage.success('添加成功')
            dialogVisible.value = false
            getBasicList()
          } else {
            ElMessage.error(res.data.message || '添加失败')
          }
        }).catch(err => {
          ElMessage.error('添加失败')
          console.error(err)
        })
        
        
        // 使用死值数据演示
        // ElMessage.success('添加成功（演示）')
        // dialogVisible.value = false
        // getBasicList()
      } else {
        // 编辑产品
        // 实际API调用代码（注释掉）
        /**/
        Traceability.post('/Basic/UpdBasic', formData).then(res => {
          if (res.data.code == 400) {
            ElMessage.success('修改基本信息成功')
            dialogVisible.value = false
            getBasicList()
          } else {
            ElMessage.error(res.data.message || '修改失败')
          }
        }).catch(err => {
          ElMessage.error('修改失败')
          console.error(err)
        })
        
        
        // 使用死值数据演示
        // ElMessage.success('修改成功（演示）')
        // dialogVisible.value = false
        // getBasicList()
      }
    }
  })
}

// 封面图上传成功处理
// const handleCoverSuccess = (response: any, file: any) => {
//   // 实际项目中应该处理上传响应
//   formData.picture = URL.createObjectURL(file.raw)
//   ElMessage.success('封面图上传成功')
// }
const handleCoverSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  formData.picture = response.data
  ElMessage.success('封面图上传成功')
}

// 封面图上传前验证
const beforeCoverUpload = (file: any) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 格式化日期时间为年月日时分秒
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return ''
  try {
    const formatted = moment(dateStr).format('YYYY-MM-DD HH:mm:ss')
    return formatted === 'Invalid date' ? dateStr : formatted
  } catch (error) {
    console.error('日期格式化错误:', error, '原始数据:', dateStr)
    return dateStr
  }
}

// 查看详情
const details = (row: BasictInfo) => {
  // 根据批次号跳转到详情页面
  router.push({
    name: 'productdetail',
    query: {
      batch: row.batch,
      id: row.id
    }
  })
}


// 分页处理函数
const handleSizeChange = (val: number) => {
  page.PageSize = val
  page.PageIndex = 1
  getBasicList()
}

const handleCurrentChange = (val: number) => {
  page.PageIndex = val
  getBasicList()
}

// 获取进度条颜色
const getProgressColor = (percentage: number) => {
  if (percentage < 30) {
    return '#f56c6c' // 红色 - 低完成度
  } else if (percentage < 60) {
    return '#e6a23c' // 橙色 - 中等完成度
  } else if (percentage < 90) {
    return '#409eff' // 蓝色 - 较高完成度
  } else {
    return '#67c23a' // 绿色 - 高完成度
  }
}
</script>

<style scoped>
/* 主容器样式 */
.basic-list-container {
  padding: 20px;
  background: #f8f9fa;
  min-height: 100vh;
}

/* 面包屑导航样式 */
.breadcrumb-nav {
  margin-bottom: 20px;
  padding: 12px 16px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.breadcrumb-nav :deep(.el-breadcrumb__item) {
  font-weight: 500;
}

.breadcrumb-nav :deep(.el-breadcrumb__item:last-child) {
  color: #2d5a27;
  font-weight: 600;
}

/* 内容包装器 */
.content-wrapper {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 操作卡片样式 */
.action-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.action-card:hover {
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
}

.action-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-btn {
  height: 36px;
  padding: 0 20px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.primary-btn {
  background: linear-gradient(135deg, #2d5a27 0%, #4a7c59 100%);
  border: none;
  color: #ffffff;
}

.primary-btn:hover {
  background: linear-gradient(135deg, #1e3d1a 0%, #3a6b47 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(45, 90, 39, 0.3);
}

.success-btn {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  border: none;
  color: #ffffff;
}

.success-btn:hover {
  background: linear-gradient(135deg, #85ce61 0%, #67c23a 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

.danger-btn {
  background: linear-gradient(135deg, #ff4757 0%, #ff3742 100%);
  border: none;
  color: #ffffff;
}

.danger-btn:hover {
  background: linear-gradient(135deg, #ff3742 0%, #ff2f3a 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 71, 87, 0.3);
}

/* 状态指示器样式 */
.status-indicators {
  display: flex;
  gap: 20px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  background: rgba(45, 90, 39, 0.1);
  border-radius: 16px;
  border: 1px solid rgba(45, 90, 39, 0.2);
}

.status-icon {
  color: #4a7c59;
  font-size: 16px;
}

.status-text {
  font-size: 12px;
  color: #2d5a27;
  font-weight: 500;
}

/* 表格卡片样式 */
.table-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.table-card:hover {
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.table-title {
  margin: 0;
  color: #2d5a27;
  font-size: 18px;
  font-weight: 600;
}

.table-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.refresh-icon {
  font-size: 18px;
  color: #4a7c59;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.refresh-icon:hover {
  background: rgba(76, 124, 89, 0.1);
  color: #2d5a27;
  transform: rotate(180deg);
}

/* 表格样式 */
.data-table {
  border-radius: 8px;
  overflow: hidden;
}

/* 表格容器样式 */
.table-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.data-table :deep(.el-table__header) {
  background: #f8f9fa;
}

.data-table :deep(.el-table__header th) {
  background: #f8f9fa !important;
  color: #2d5a27;
  font-weight: 600;
  border-bottom: 2px solid #e9ecef;
}

.data-table :deep(.el-table__row:hover) {
  background: rgba(76, 124, 89, 0.05) !important;
}

.data-table :deep(.el-table__row) {
  transition: all 0.3s ease;
}

/* 列头样式 */
.column-header {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: center;
}

.column-title {
  font-weight: 600;
  color: #2d5a27;
  font-size: 14px;
}

.search-input {
  width: 100%;
  max-width: 120px;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid #e9ecef;
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper:hover) {
  border-color: #4a7c59;
}

.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: #2d5a27;
  box-shadow: 0 0 0 2px rgba(45, 90, 39, 0.1);
}

/* 操作按钮单元格样式 */
.action-buttons-cell {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  justify-content: center;
}

.table-action-btn {
  height: 28px;
  padding: 0 12px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.detail-btn {
  background: linear-gradient(135deg, #409eff 0%, #5a9eff 100%);
  border: none;
  color: #ffffff;
}

.detail-btn:hover {
  background: linear-gradient(135deg, #5a9eff 0%, #409eff 100%);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.edit-btn {
  background: linear-gradient(135deg, #e6a23c 0%, #f0c040 100%);
  border: none;
  color: #ffffff;
}

.edit-btn:hover {
  background: linear-gradient(135deg, #f0c040 0%, #e6a23c 100%);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(230, 162, 60, 0.3);
}

.export-btn {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  border: none;
  color: #ffffff;
}

.export-btn:hover {
  background: linear-gradient(135deg, #85ce61 0%, #67c23a 100%);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
}

.delete-btn {
  background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
  border: none;
  color: #ffffff;
}

.delete-btn:hover {
  background: linear-gradient(135deg, #f78989 0%, #f56c6c 100%);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.3);
}

/* 分页样式 */
.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 16px 0;
}

.custom-pagination :deep(.el-pagination) {
  --el-pagination-bg-color: #ffffff;
  --el-pagination-text-color: #2d5a27;
  --el-pagination-border-radius: 8px;
  --el-pagination-button-bg-color: #f8f9fa;
  --el-pagination-button-color: #2d5a27;
  --el-pagination-hover-color: #4a7c59;
}

.custom-pagination :deep(.el-pagination .el-pager li.is-active) {
  background: linear-gradient(135deg, #2d5a27 0%, #4a7c59 100%);
  color: #ffffff;
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 0;
}

/* 上传组件样式 */
.cover-uploader {
  width: 100%;
}

.cover-upload-box {
  width: 160px;
  height: 160px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  transition: all 0.3s ease;
}

.cover-upload-box:hover {
  border-color: #4a7c59;
  background: linear-gradient(135deg, #e9ecef 0%, #f8f9fa 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(76, 124, 89, 0.2);
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  transition: color 0.3s ease;
}

.cover-upload-box:hover .cover-uploader-icon {
  color: #4a7c59;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .basic-list-container {
    padding: 12px;
  }
  
  .action-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .action-buttons {
    justify-content: center;
  }
  
  .status-indicators {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .action-buttons-cell {
    flex-direction: column;
    gap: 4px;
  }
  
  .table-action-btn {
    width: 100%;
    margin: 0;
  }
}

/* 进度条样式 */
.completeness-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 8px 0;
}

.completeness-progress {
  width: 100%;
  max-width: 120px;
}

.completeness-progress :deep(.el-progress__text) {
  font-size: 12px;
  font-weight: 600;
  color: #2d5a27;
}

.completeness-progress :deep(.el-progress-bar__outer) {
  background-color: rgba(45, 90, 39, 0.1);
  border-radius: 4px;
}

.completeness-progress :deep(.el-progress-bar__inner) {
  border-radius: 4px;
  transition: all 0.3s ease;
}

/* 通用按钮间距 */
.el-button + .el-button {
  margin-left: 8px;
}
</style>
